package com.topisv.tms.web;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.BackupTask;
import com.topisv.tms.entity.BackupTaskOrdeno;
import com.topisv.tms.entity.BackupTaskSku;
import com.topisv.tms.entity.BatchTask;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.OrdenoSource;
import com.topisv.tms.entity.ShippedBoxSkus;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.entity.dto.BackupTaskSkuDTO;
import com.topisv.tms.entity.dto.ShippedBoxDTO;
import com.topisv.tms.service.BackupTaskOrdenoService;
import com.topisv.tms.service.BackupTaskService;
import com.topisv.tms.service.BackupTaskSkuService;
import com.topisv.tms.service.BatchTaskService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.OrdenoSourceService;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.shipped.ShippedBoxService;
import com.topisv.tms.service.shipped.ShippedBoxSkusService;
import com.topisv.tms.utils.TimeUtil;
import com.topisv.tms.utils.date.TopIsvDateUtils;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.utils.store.GetSkuStoreUtil;
import com.topisv.tms.web.dto.GroupBackupTaskDTO;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/backupTask")
public class BackupTaskController {
	
	private static final Logger log = LoggerFactory.getLogger(BackupTaskController.class);
	
	private static int PAGENUMBER = 100;

	@Autowired
	private BackupTaskService backupTaskService;
	@Autowired
	private BackupTaskSkuService backupTaskSkuService;
	@Autowired
	private ShippedBoxService shippedBoxService;
	@Autowired
	private BatchTaskService batchTaskService;
	@Autowired
	private BackupTaskOrdenoService backupTaskOrdenoService;
	@Autowired
	private ShippedBoxSkusService shippedBoxSkusService;
	@Autowired
	private ShopSourceService shopSourceService;
	@Autowired
	private EdiOrderService ediOrderService;
	@Autowired
	private OrdenoSourceService ordenoSourceService;

	/**
	 * 一键拣货
	 * 
	 * @param backupTaskCode
	 * @param response
	 */
	@RequestMapping(value = "ajaxPickingCode")
	public void ajaxPickingCode(
			@RequestParam(value = "backupTaskCode") String backupTaskCode,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		BackupTask backupTask =null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			backupTask =backupTaskService.findByBackupTaskCode(backupTaskCode);
			if (backupTask == null) {
				json.put("status", "1");
				json.put("content", "该拣货任务不存在");
				out.print(json.toString());
				return;
			}
			if ("finish".equals(backupTask.getPickStatus())) {
				json.put("status", "1");
				json.put("content", "该拣货任务已经完成拣货");
				out.print(json.toString());
				return;
			}
			if ("working".equals(backupTask.getPickStatus())) {
				json.put("status", "1");
				json.put("content", "生成拣货任务中");
				out.print(json.toString());
				return;
			}
			backupTask.setPickStatus("working");
			backupTaskService.save(backupTask);
			String content = backupTaskService.pickBackupTaskSku(backupTaskCode);
			
			if(!"拣货成功".equals(content)){
				backupTask.setPickStatus("pending");
				backupTaskService.save(backupTask);
				json.put("status", "0");
				json.put("content", content);
				out.print(json.toString());
				return;
			}
			
			json.put("status", "1");
			json.put("content", content);

			out.print(json.toString());
		} catch (Exception e) {
			backupTask.setPickStatus("pending");
			backupTaskService.save(backupTask);
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	/**
	 * 商品拣货
	 * 
	 * @param backupTaskCode
	 * @param sku
	 * @param number
	 * @param response
	 */
	@RequestMapping(value = "ajaxPickingSku")
	public void ajaxPickingSku(
			@RequestParam(value = "backupTaskCode") String backupTaskCode,
			@RequestParam(value = "sku") String sku,
			@RequestParam(value = "number") int number,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			BackupTaskSkuDTO backupTaskSkuDTO = backupTaskService.pickBackupTaskSku(backupTaskCode, sku, number);
			if (backupTaskSkuDTO == null) {
				json.put("status", "-1");
				json.put("content", "拣货失败:该商品不属于该拣货任务");
				out.print(json.toString());
				return;
			}

			if ("-1".equals(backupTaskSkuDTO.getStatus())) {
				json.put("status", "-1");
				json.put("content", backupTaskSkuDTO.getReserve());
			} else {
				json.put("status", "1");
				json.put("content", backupTaskSkuDTO.getReserve());
			}
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}
	
	
	@RequestMapping(value = "showOrdenos/{backupTaskCode}")
	public String showOrdenos(
			@PathVariable(value = "backupTaskCode") String backupTaskCode,
			Model model) {
		List<BackupTaskOrdeno> backupTaskOrdenos = null;
		List<EdiOrder> ediOrders=null;
		try {
			ediOrders=new ArrayList<EdiOrder>();
			backupTaskOrdenos = backupTaskOrdenoService.findByBackupTaskCode(backupTaskCode);
			for(BackupTaskOrdeno b:backupTaskOrdenos){
				ediOrders.add(ediOrderService.findByOrdeno(b.getOrdeno()));
			}
			model.addAttribute("object", ediOrders);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}

		return "backupTask/showOrdenos";
	}
	

	/**
	 * 显示拣货列表
	 * 
	 * @param backupTaskCode
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "pickingSku/{backupTaskCode}")
	public String pickingSku(
			@PathVariable(value = "backupTaskCode") String backupTaskCode,
			Model model) {
		ShiroUser user = getShiroUser();
		BackupTask backupTask = null;
		List<BackupTaskSku> backupTaskSkus = null;
		try {
			backupTask = backupTaskService.setJobuuid(backupTaskCode, user.jobuuid, "picking");
			if (backupTask == null) {
				return "redirect:/backupTask/backupTaskLists";
			} else {
				model.addAttribute("obj", backupTask);
				backupTaskSkus = backupTaskSkuService.findByBackupTaskCode(backupTaskCode);
				model.addAttribute("backupTaskSkus", backupTaskSkus);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}

		return "backupTask/pickingSku";
	}

	/**
	 * 显示未处理的拣货任务
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "backupTaskLists")
	public String backupTask(Model model) {
		String status = "pending";// 未处理的拣货任务
		ShiroUser user = getShiroUser();
		List<BackupTask> backupTasks = null;
		try {
			if (StatusEnums.user_type_paiu.getStatus().equals(user.userType)) {//派友用户
				backupTasks = backupTaskService.findBackupTaskStatus(user.customers, user.areagroups, status);
			} else if(StatusEnums.user_type_customer.getStatus().equals(user.userType)){//商家用户
				backupTasks = backupTaskService.findByStatusAndCustomerCode(status, user.customerCode);
			}
			setAreaGroupName(backupTasks);
			model.addAttribute("object", backupTasks);
			model.addAttribute("status", 1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}
		return "backupTask/backupTaskLists";
	}
	
	private void setAreaGroupName(List<BackupTask> backupTasks ) throws Exception{
		try {
			if(backupTasks==null){
				return;
			}
			for(BackupTask b:backupTasks){
				BatchTask batchTask=batchTaskService.findByBatchTaskCode(b.getBatchTaskCode());
				b.setAreaGroupName(batchTask.getAreaGroupName());
			}
		} catch (Exception e) {
			throw e;
		}
	}
	
	private List<BackupTask> getBackupTasks(List<BackupTask> backupTasks,String customerCode)throws Exception{
		List<BackupTask> tempBackupTask=new ArrayList<BackupTask>();
		try {
			for(BackupTask b:backupTasks){
				if(customerCode.equals(b.getCustomerCode())){
					tempBackupTask.add(b);
				}
			}
			return tempBackupTask;
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 根据拣货任务号获得商品信息
	 * 
	 * @param backupTaskCode
	 * @param response
	 */
	@RequestMapping(value = "ajaxPrintBackupTaskSkus")
	public void ajaxPrintBackupTaskSkus(
			@RequestParam(value = "backupTaskCode") String backupTaskCode,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		ShiroUser user = getShiroUser();

		try {
			json = new JSONObject();
			out = response.getWriter();
			List<BackupTaskSku> backupTaskSkus = backupTaskSkuService
					.findByBackupTaskCode(backupTaskCode);
			if (backupTaskSkus.isEmpty()) {
				json.put("status", "-1");
				json.put("content", "请检查备货任务号是否正确");
				out.print(json.toString());
				return;
			}
			BackupTask backupTask = backupTaskService.findByBackupTaskCode(backupTaskCode);
			BatchTask batchTask = batchTaskService.findByBatchTaskCode(backupTask.getBatchTaskCode());
			OrdenoSource ordenoSource=ordenoSourceService.findByOrdenoSourceCode(batchTask.getShopSourceCode());
			ShopSource shopSource = shopSourceService.findByOrdenoSourceCode(ordenoSource.getOrdenoSourceCode()).get(0);//根据店铺编码获取店铺信息
			
			// 获得库存信息
			GetSkuStoreUtil.getSkuStoreCode(backupTaskSkus, shopSource);
			
			
			if("single".equals(batchTask.getType())){
				batchTask.setType("单件");
			}else if("multiple".equals(batchTask.getType())){
				batchTask.setType("多件");
			}
			
			if(StatusEnums.FWAREHOUSE.getStatus().equals(batchTask.getBatchType())){
				batchTask.setBatchType("分仓订单");
			}else{
				batchTask.setBatchType("总仓订单");
			}
			
			json.put("status", "1");
			json.put("content", backupTaskSkus);
			json.put("batchTask", batchTask);
			json.put("backupTask", backupTask);
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	
	@RequestMapping(value = "backupTaskLists/{from}")
	public String list(
			@PathVariable("from") String from,
			@RequestParam(value = "sortType", defaultValue = "auto") String sortType,
			@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			Model model, ServletRequest request) {
		Date startDate = null;
		Date endDate = null;
		ShiroUser user = getShiroUser();
		List<BackupTask> backupTasks = null;
		Page<BackupTask> pageBackupTasks = null;
		try {
			Map<String, Object> searchParams = Servlets
					.getParametersStartingWith(request, "search_");
			
			if (StatusEnums.user_type_paiu.getStatus().equals(user.userType)) {//派友用户
				if ("pending".equals(from)) {
					String status="status";
					backupTasks = backupTaskService.findBackupTaskStatus(user.customers, user.areagroups, status);
					setAreaGroupName(backupTasks);
					model.addAttribute("status", 1);
					model.addAttribute("object", backupTasks);
				} else {
					startDate = TimeUtil.getDate(from);
					endDate = TopIsvDateUtils.addDays(startDate, 1);
					String type=(String)searchParams.get("EQ_type");//类型
					String userName=(String)searchParams.get("LIKE_username");//用户名
					pageBackupTasks = backupTaskService.getPageBackupTasks(pageNumber,PAGENUMBER, sortType, startDate, endDate,type,userName,user.customers,user.areagroups);
					setAreaGroupName(pageBackupTasks.getContent());
					model.addAttribute("status", 0);
					model.addAttribute("from", from);
					model.addAttribute("object", pageBackupTasks);
				}
			} else if(StatusEnums.user_type_customer.getStatus().equals(user.userType)){//商家用户
     				searchParams.put("EQ_customerCode", user.customerCode);

				if ("pending".equals(from)) {
					searchParams.put("EQ_status", "pending");
					backupTasks = backupTaskService.getPageBackupTasks(searchParams);
					setAreaGroupName(backupTasks);
					model.addAttribute("status", 1);
					model.addAttribute("object", backupTasks);
				} else {
					startDate = TimeUtil.getDate(from);
					endDate = TopIsvDateUtils.addDays(startDate, 1);
					pageBackupTasks = backupTaskService.getPageBackupTasks(searchParams, pageNumber, PAGENUMBER, sortType,startDate, endDate);
					setAreaGroupName(pageBackupTasks.getContent());
					model.addAttribute("status", 0);
					model.addAttribute("from", from);
					model.addAttribute("object", pageBackupTasks);
				}
			}
			
			
		
			model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}
		return "backupTask/backupTaskLists";

	}

	/**
	 * 已经装箱的商品发生变化
	 * 
	 * @param boxCode
	 * @param skuId
	 * @param index
	 * @param backupTaskCode
	 * @param response
	 */
	@RequestMapping(value = "ajaxChangeBoxCodeSkus")
	public void ajaxInitReduceSkus(
			@RequestParam(value = "boxCode") String boxCode,
			@RequestParam(value = "skuId") String skuId,
			@RequestParam(value = "index") int index,
			@RequestParam(value = "backupTaskCode") String backupTaskCode,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		ShippedBoxDTO shippedBox = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			if (index == 1) {// 箱子新增商品
				shippedBox = shippedBoxService.addShippedBoxSkuId(boxCode,skuId);
			} else if (index == 0) {// 箱子减少商品
				shippedBox = shippedBoxService.reduceShippedBoxSkuId(boxCode,skuId);
			}
			if (shippedBox == null) {
				json.put("status", "-1");
				json.put("content", "该箱子不存在");
				out.print(json.toString());
				return;
			} else if ("-1".equals(shippedBox.getStatus())) {
				json.put("status", "-1");
				json.put("content", shippedBox.getReserve());
				out.print(json.toString());
				return;
			}else if("finish".equals(shippedBox.getStatus())){
				json.put("index", "1");

			}else if("pending".equals(shippedBox.getStatus())){
				json.put("index", "-1");

			}
			json.put("status", "1");
			json.put("content", shippedBox);
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	/**
	 * 根据箱子编码获得箱子商品信息
	 * 
	 * @param boxCode
	 * @param response
	 */
	@RequestMapping(value = "ajaxInitReduceSkus")
	public void ajaxInitReduceSkus(
			@RequestParam(value = "boxCode") String boxCode,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;

		try {
			json = new JSONObject();
			out = response.getWriter();
			List<ShippedBoxSkus> shippedBoxSkus = shippedBoxSkusService.findByBoxCode(boxCode);
			if (shippedBoxSkus.isEmpty()) {
				json.put("status", "-1");
				json.put("content", "箱子编码有误");
				out.print(json.toString());
				return;
			}

			json.put("status", "1");
			json.put("content", shippedBoxSkus);
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	/**
	 * 对任务进行分组
	 * 
	 * @param batchTaskCode
	 * @param number
	 * @param response
	 */
	@RequestMapping(value = "ajaxGroupBackupTask")
	public void ajaxGroupBackupTask(
			@RequestParam(value = "batchTaskCode") String batchTaskCode,
			@RequestParam(value = "number", defaultValue = "100") int number,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		BatchTask batchTask = null;
		List<GroupBackupTaskDTO> groupBackupTaskDTOs = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			batchTask = batchTaskService.findByBatchTaskCode(batchTaskCode);
			if (batchTask == null) {
				json.put("status", "-1");
				json.put("content", "该拣货批次不存在");
				out.print(json.toString());
				return;
			}
			groupBackupTaskDTOs = backupTaskService.getGroupBackupTasks(batchTaskCode, number,batchTask.getCustomerCode());
			if (groupBackupTaskDTOs.isEmpty()) {
				json.put("status", "-1");
				json.put("content", "该拣货批次订单数为0");
				out.print(json.toString());
				return;
			}
			json.put("status", "1");
			json.put("content", groupBackupTaskDTOs);
			out.print(json.toString());
		} catch (Exception e) {
			batchTask.setStatus("pending");
			batchTaskService.save(batchTask);
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	/**
	 * 生成拣货任务
	 * 
	 * @param batchTaskCode
	 * @param number
	 * @param response
	 */
	@RequestMapping(value = "ajaxCreateBackupTask")
	public void ajaxCreateBackupTask(
			@RequestParam(value = "batchTaskCode") String batchTaskCode,
			@RequestParam(value = "groups") String groups,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		ShiroUser user = getShiroUser();
		BatchTask batchTask = null;
		List<BackupTaskOrdeno> backupTaskOrdenos = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			log.info("生成拣货任务开始--分拣批次号:"+batchTaskCode+"====groups="+groups);
			batchTask = batchTaskService.findByBatchTaskCode(batchTaskCode);
			if (batchTask == null) {
				json.put("status", "-1");
				json.put("content", "该拣货批次不存在");
				out.print(json.toString());
				return;
			}

			if ("finish".equals(batchTask.getStatus())) {
				json.put("status", "-1");
				json.put("content", "该拣货批次已经生成了拣货任务");
				out.print(json.toString());
				return;
			}
			if ("working".equals(batchTask.getStatus())) {
				json.put("status", "-1");
				json.put("content", "拣货任务生成进行中");
				out.print(json.toString());
				return;
			}
			batchTask.setStatus("working");
			batchTaskService.save(batchTask);
			backupTaskOrdenos = backupTaskOrdenoService
					.findByBatchTaskCode(batchTaskCode);
			if (backupTaskOrdenos.isEmpty()) {
				json.put("status", "-1");
				json.put("content", "生成拣货任务批次错误");
				out.print(json.toString());
				return;
			}
			List<BackupTask> backupTasks = null;//backupTaskService.createBachupTask(backupTaskOrdenos, user.jobuuid, batchTask, groups);
			
			if (backupTasks.isEmpty()) {
				json.put("status", "-1");
				json.put("content", "生成拣货任务批次错误");
				out.print(json.toString());
				return;
			}
			json.put("status", "1");
			json.put("content", backupTasks.size());
			out.print(json.toString());
			
		} catch (Exception e) {
			batchTask.setStatus("pending");
			batchTaskService.save(batchTask);
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}
	
	/**
	 * 导出exl表格
	 * 
	 * @param batchcode
	 * @param response
	 */
	@RequestMapping(value = "exportExcel/{backupTaskCode}")
	public void exportExcel(
			@PathVariable("backupTaskCode") String backupTaskCode,
			HttpServletResponse response) {
		List<BackupTaskOrdeno> backupTaskOrdenos = null;
		BackupTask backupTask = null;
		BatchTask batchTask=null;
		try {
			backupTask = backupTaskService.findByBackupTaskCode(backupTaskCode);
			batchTask=batchTaskService.findByBatchTaskCode(backupTask.getBatchTaskCode());
			backupTaskOrdenos = backupTaskOrdenoService.findByBackupTaskCode(backupTaskCode);

			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-disposition", "attachment; filename="+ backupTaskCode + ".xls");
			WritableWorkbook book = Workbook.createWorkbook(response
					.getOutputStream());
			WritableSheet sheet = book.createSheet("第一页", 0);

			WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 10,WritableFont.BOLD);
			WritableCellFormat wcf_center = new WritableCellFormat(BoldFont);
			int length = backupTaskOrdenos.size();

			sheet.addCell(new Label(0, 0, batchTask.getAreaGroupName()+"  共计：" + Integer.toString(length)+ " 单", wcf_center));

			sheet.setColumnView(0, 22);
			sheet.setColumnView(1, 15);
			sheet.setColumnView(2, 12);
			sheet.setColumnView(3, 18);
			sheet.setColumnView(4, 12);
			sheet.addCell(new Label(0, 1, "拣货批次号"));
			sheet.addCell(new Label(1, 1, "订单号"));
			sheet.addCell(new Label(2, 1, "来源单号"));
			sheet.addCell(new Label(3, 1, "时间"));
			sheet.addCell(new Label(4, 1, "能容运单号"));
			sheet.addCell(new Label(5, 1, "收件人名称"));
			sheet.addCell(new Label(6, 1, "收件人地址"));
			sheet.addCell(new Label(7, 1, "收件人手机"));

			DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			for (int i = 0; i < length; i++) {
				EdiOrder ediOrder = ediOrderService.findByOrdeno(backupTaskOrdenos.get(i).getOrdeno());
				sheet.addCell(new Label(0, i + 2, ediOrder.getBackupTaskCode()));//拣货批次号

				sheet.addCell(new Label(1, i + 2, ediOrder.getOrdeno()));//订单号
				sheet.addCell(new Label(2, i + 2, ediOrder.getFromno()));//来源单号
				String creatTime = format.format(ediOrder.getCrtime());//时间
				sheet.addCell(new Label(3, i + 2, creatTime));
				sheet.addCell(new Label(4, i + 2, ediOrder.getWaybillNo()));//能容运单号
				sheet.addCell(new Label(5, i + 2, ediOrder.getRecena()));//收件人名称
				sheet.addCell(new Label(6, i + 2, ediOrder.getAddres()));//收件人地址
				sheet.addCell(new Label(7, i + 2, ediOrder.getMobile()));//收件人手机
				
			}
			book.write();
			book.close();
		} catch (Exception e) {
			
		}
	}


	/**
	 * 取出Shiro中的当前用户Id.
	 */
	private ShiroUser getShiroUser() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user;
	}

}
